package com.yiba.vpn.controller;

import com.wordnik.swagger.annotations.ApiOperation;
import com.yiba.vpn.authorization.manager.TokenManager;
import com.yiba.vpn.config.Constants;
import com.yiba.vpn.service.MonitorWebService;
import com.yiba.vpn.util.Iputil;
import com.yiba.vpn.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

/**
 * 元旦活动期间 访问的IP 监控
 *
 * @author zws
 */
@Controller
@RequestMapping(value = "monitor")
public class MonitorWebController {

    private Logger LOGGER = LoggerFactory.getLogger(MonitorWebController.class);

    @Autowired
    private MonitorWebService monitorWebService;

    @Autowired
    private TokenManager tokenManager;

    private String IP_ = "ip_";

    private Logger logger = LoggerFactory.getLogger(MonitorWebController.class);

    @RequestMapping(value = "/vist", method = RequestMethod.GET)
    @ApiOperation(value = "web登录记录")
    @ResponseBody
    public void vist(HttpServletRequest request) {
        String xfor = request.getHeader("x-forwarded-for");
        String ipforward = xfor == null ? null : xfor.split(",")[0];
        logger.error("ipforward  >>" + ipforward);

        String ip = ipforward ==null ? Iputil.getRequestIp(request):ipforward;
        if ("0:0:0:0:0:0:0:1".equals(ip) || "127.0.0.1".equals(ip)) {
            return;
        }


        String value = tokenManager.getValue(IP_ + ip);
        if (StringUtils.isNullOrEmpty(value)) {
            tokenManager.addV(IP_ + ip, 1 + "", Constants.IP_EXPIRES_SECONDS, TimeUnit.SECONDS);
        } else {
            return;
        }
        monitorWebService.vistRecord(ip);

    }
}
